package info.techgeek.labs.patterns.serviceLocatorPattern1;

/*
 * @author                        : Neelesh
 * @Version                       : 2.0
 *
 * Development Environment        : Oracle9i JDeveloper

 * Name of the File               : ServiceLocator.java
 * Creation/Modification History  :
 *
 * Neelesh  03-March-2003      Created
 *
 */


// Java utility class
import java.util.Hashtable;

// JNDI classes
import javax.naming.InitialContext;
import javax.naming.NamingException;



/**
 * This class is implemented as a singleton class and is a central place for
 * looking up objects in the JNDI tree.
 *
 * @author Neelesh
 * @version 2.0
 */

public class ServiceLocator {

  // Singleton instance
  private static ServiceLocator serviceLocator = new ServiceLocator();

  // Cache of objects in JNDI tree
  private Hashtable homeCache;

  // Initial context
  private InitialContext defaultContext;


  /**
   * Private constructor, which initializes all the tables and the default
   * InitialContext.
   */
  private ServiceLocator() {

    try {
      homeCache        = new Hashtable();
      defaultContext   = new InitialContext();
    } catch(Exception ex) {

      System.out.println("Exception in the constructor of ServiceLocator " +
                         "class : " + ex.toString());
    }
  }

  /**
   * Method to access the Singleton instance of the ServiceLocator
   *
   * @return <b>ServiceLocator</b> The instance of this class
   */
  public static ServiceLocator getLocator() {


    return serviceLocator;
  }
  /**
   * Method to return an object in the default JNDI context, with  the supplied
   * JNDI name.
   *
   * @param <b>jndiName</b> The JNDI name
   *
   * @return <b>Object</b> The object in the JNDI tree for this name.
   *
   * @throws <b>UtilityException</b> Exception this method can throw
   */
  public Object getService(String jndiName) {


    try {

      if(!homeCache.containsKey(jndiName)) {

        // If the service is not in the cache, get the object for the 
        // supplied jndi name and put it in the cache
        homeCache.put(jndiName, defaultContext.lookup(jndiName));
      }
    } catch(NamingException ex) {
      
    } catch(SecurityException ex) {

    
    }

    // Return object from cache
    return homeCache.get(jndiName);
  }
}